<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filter" id="form">
        <el-form-item>
          <el-input v-model="filter.keyword" placeholder="关键词查询"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-refresh" @click="resetForm">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-circle-plus-outline" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" round icon="el-icon-sell" @click="onsale" :loading="loading">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" round icon="el-icon-sold-out" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="handleSelectionChange"
              border style="width: 100%;" :row-key="getRowKey" @row-dblclick="drawerClick">
      <el-table-column :reserve-selection="true" type="selection" width="55"></el-table-column>
      <el-table-column type="index" width="60" label="序号"></el-table-column>
      <el-table-column prop="name" min-width="40px" label="服务项目"></el-table-column>
      <el-table-column prop="costprice" label="成本价" min-width="30px"></el-table-column>
      <el-table-column prop="saleprice" label="销售价" min-width="30px"></el-table-column>
      <el-table-column prop="salecount" label="销售量" min-width="25px"></el-table-column>
      <el-table-column prop="resources" label="图片" align="center" min-width="40px">
        <template slot-scope="scope">
          <el-image style="width:auto;height:auto " :src="imgPrefix+scope.row.resources.split(',')[0]"/>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" align="center" min-width="40px"></el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" align="center" min-width="40px"></el-table-column>
      <el-table-column prop="createtime" label="创建时间" align="center" min-width="40px"></el-table-column>
      <el-table-column align="center" sortable prop="state" label="状态" min-width="50">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state==1?true:false" active-color="#13ce66" inactive-color="#ff4949"
                     @change="editType(scope.$index, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--     抽屉-->
    <el-drawer
        title="CoderYeah"
        :visible.sync="table"
        direction="rtl"
        size="30%">
      <el-divider><span><i class="el-icon-ice-tea"/></span><i class="el-icon-ice-drink"/><i class="el-icon-milk-tea"/>
      </el-divider>
      <el-table :data="gridData">
        <el-table-column property="resources" label="宠物图片" min-width="100px">
          <template scope="scope">
            <div class="block">
              <el-image :src="imgPrefix+scope.row.resources">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>

            <!--            <img :src="imgPrefix+scope.row.resources" width="100%" class="image" alt="加载失败">-->
            <!--            <div slot="error" class="image-slot">-->
            <!--              <i class="el-icon-picture-outline"></i>-->
            <!--            </div>-->
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" icon="el-icon-delete-solid" @click="batchRemove" :disabled="this.sels.length===0">批量删除
      </el-button>
      <!--      style="float:right;-->

      <!--  分页插件  -->
      <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :total="total" :current-page="currentPage" :page-size="pageSize"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="pageSizes"
          style="float:right">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false" width="60%" @close="cancel">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="服务名称" prop="name">
          <el-input prefix-icon="el-icon-tickets" v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input-number :min="0" oninput="if(value<0)value=0" v-model.trim="editForm.costprice"
                           auto-complete="off"></el-input-number>
        </el-form-item>
        <el-form-item label="销售价" prop="saleprice">
          <el-input-number :min="0" oninput="if(value<0)value=0" v-model.trim="editForm.saleprice"
                           auto-complete="off"></el-input-number>
        </el-form-item>
        <el-form-item label="销售量">
          <el-input-number :min="0" oninput="if(value<0)value=0" v-model.trim="editForm.salecount"
                           auto-complete="off"></el-input-number>
        </el-form-item>

        <el-form-item label="图片" prop="index">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs/"
                     :on-preview="handlePreview"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="上架时间" prop="onsaletime">
          <div class="block">
            <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="editForm.onsaletime"
                type="datetime"
                placeholder="选择日期时间"
                align="right"
                :picker-options="pickerOptions">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="下架时间" prop="offsaletime">
          <div class="block">
            <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="editForm.offsaletime"
                type="datetime"
                placeholder="选择日期时间"
                align="right"
                :picker-options="pickerOptions">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="服务简介" prop="intro">
          <!-- v-if="saveForm.ProductDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor v-model="editForm.productDetail.intro" v-if="editForm.productDetail"
                        :options="quillOption"></quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="orderNotice">
          <quill-editor v-model="editForm.productDetail.orderNotice" v-if="editForm.productDetail"
                        :options="quillOption"></quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="cancel">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
//引入Vue的ueditor的资源
import {quillEditor} from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      loading: false,
      quillOption: quillConfig,
      gridData: [],
      //列表显示图片的前缀
      imgPrefix: "http://123.207.27.208",
      table: false,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      value2: '',

      filter: {
        keyword: ''
      },
      value: '',
      title: '新增',
      products: [],
      shops: [],
      users: [],
      ProductTyProductree: [],
      //文件上传相关数据
      fileList: [],
      total: 0,
      currentPage: 1,
      pageSize: 5,
      pageSizes: [5, 10, 20, 50, 100],
      listLoading: true,
      sels: [],//列表选中列

      editFormVisible: false,// 编辑/添加界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          {required: true, message: '请输入宠物名称', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入成本价', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入销售价', trigger: 'blur'}
        ],
        type: [
          {required: false, message: '请选择宠物类型', trigger: 'blur'}
        ],
        onsaletime: [
          {required: false, message: '请选择上架时间', trigger: 'blur'}
        ],
        offsaletime: [
          {required: false, message: '请选择下架时间', trigger: 'blur'}
        ],
        shop: [
          {required: false, message: '请选择所属店铺', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      editForm: {
        id: null,
        name: '',
        resources: '',
        saleprice: '',
        costprice: '',
        onsaletime: '',
        offsaletime: '',
        salecount: '',
        productDetail: {  //与后端实体类一致
          id: null,
          intro: '',
          orderNotice: ''
        }
      },
    }
  },
  methods: {
    // 上架
    onsale() {
      if (this.sels.length === 0) {
        this.$message.error('请选择数据后操作哦')
        return
      }
      this.$confirm('确认上架选择的所有记录吗？', '提示', {type: "warning"}).then(res => {
        // 获取需要上架的所有id
        let ids = this.sels.map(m => m.id);
        this.$http.post('/product/onsale', ids).then((res) => {
          this.loading = true
          if (res.data.success) {
            this.$message.success('上架成功')
            this.getProducts()
            this.loading = false
          } else {
            this.$message.error('上架失败')
            this.getProducts()
            this.loading = false
          }
        }).catch(e => {
          this.$message.error('系统错误，请稍后重试【400】【403】【404】【405】!!!')
        })
      })
    },

    // 下架
    offsale() {
      if (this.sels.length === 0) {
        this.$message.error('请选择数据后操作哦')
        return
      }
      this.$confirm('确认下架选择的所有记录吗？', '提示', {type: "warning"}).then(res => {
        // 获取需要下架的所有id
        let ids = this.sels.map(m => m.id);
        this.$http.post('/product/offsale', ids).then((res) => {
          if (res.data.success) {
            this.$message.success('下架成功')
            this.getProducts()
          } else {
            this.$message.error('下架失败')
            this.getProducts()
          }
        }).catch(e => {
          this.$message.error('系统错误，请稍后重试【400】【403】【404】【405】!!!')
        })
      })
    },

    clear() {
      this.sels = []
    },
    drawerClick(row) {
      this.gridData = [
        {
          'resources': row.resources.split(',')[0]
        }
      ]
      this.table = true
    },

    //文件上传的业务逻辑
    handleSuccess(response, file, fileList) {
      // 上传多张图片需要对resources进行处理,多张图片保存到数据库的resources字段用,隔开
      if (this.editForm.resources) {
        // 对已经存在的图片进行拼接
        this.editForm.resources = this.editForm.resources + "," + response.data
      } else {
        this.editForm.resources = response.data
      }
      console.log(this.editForm.resources)
      // 对fileList进行处理，用以显示图片
      // 先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      this.fileList = []
      if (this.editForm.resources) {
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg 对其进行分割
        let arr = this.editForm.resources.split(',')
        // 循环遍历
        for (let i = 0; i < arr.length; i++) {
          // 从fastDfs文件系统获取资源
          this.fileList.push({'url': 'http://123.207.27.208' + arr[i]})
        }
      }
    },

    //文件删除的业务逻辑
    handleRemove(file, fileList) {
      // url:"http://123.207.27.208/group1/M00/01/D0/CgAIC2MwX7eAWEwlAACO89rfJDY938.jpg"
      console.log(file);
      const filePath = file.url.substring(file.url.indexOf('/group'))// /group1/M00/01/D0/CgAIC2MwX7eAWEwlAACO89rfJDY938.jpg
      this.$http.delete("/fastDfs?path=" + filePath)
          .then(res => {
            if (res.data.success) {
              this.$message.success("删除成功")
            } else {
              this.$message.error("删除失败")
            }
          });
      // 删除之后对resources做处理
      if (this.editForm.resources) {
        let arr = this.editForm.resources.split(',');
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] == filePath) {//找到了删除的图片
            arr.splice(i, 1);//删除数组中指定的图片
            // 跳出循环
            break;
          }
        }
        // 对resources重新拼接
        this.editForm.resources = arr.join(',')
      }
      console.log("删除后的resources:" + this.editForm.resources);

      // 对fileList进行处理，用以显示图片
      // 先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      this.fileList = []
      if (this.editForm.resources) {
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg 对其进行分割
        let arr = this.editForm.resources.split(',')
        // 循环遍历
        for (let i = 0; i < arr.length; i++) {
          // 从fastDfs文件系统获取资源
          this.fileList.push({'url': 'http://123.207.27.208' + arr[i]})
        }
      }
    },

    //图片预览
    handlePreview(file) {
      console.log(file);
    },


    getRowKey(row) {
      return row.id;
    },
    //重置表单
    resetForm() {
      this.filter.keyword = ''
      this.getProducts()
    },

    // 取消操作
    cancel() {
      this.editForm.id = null
      this.editForm.name = ''
      this.editForm.saleprice = ''
      this.editForm.onsaletime = ''
      this.editForm.offsaletime = ''
      this.editForm.resources = ''
      this.editForm.costprice = ''
      this.fileList = []
      this.editForm.productDetail = {  //与后端实体类一致
        id: null,
        intro: '',
        orderNotice: ''
      }
      this.editFormVisible = false
    }
    ,
    // 查询
    search() {
      this.currentPage = 1
      if (this.filter.keyword.trim().length < 1) {
        this.filter.keyword = ''
        this.$message.info("请输入查询条件")
        return;
      }
      this.getProducts()
    }
    ,
    //状态修改
    editType(index, row) {
      console.log(index + ":" + row.state + ":" + row.id)
      let param = {
        state: row.state,
        id: row.id
      }
      //发送请求
      this.$http.post('/product/editType', param).then((res) => {
        if (res.data.success) {
          this.$message({
            message: '修改状态成功',
            type: 'success'
          })
        }
      }).catch(reason => {
        this.$message.error(reason.message);
      }).finally(r => {
        this.getProducts()
      })
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getProducts();
    }
    ,
    // 当前页数量改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.getProducts()
    }
    ,
    //获取用户列表
    getProducts() {
      this.listLoading = true
      // 分页请求参数
      let param = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        id: this.editForm.id,
        keyword: this.filter.keyword
      };
      this.$http.post('/product/list', param).then(res => {
        console.log(res.data);
        this.products = res.data.data
        this.total = res.data.totals
      });
      this.listLoading = false
    }
    ,
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = {id: row.id};
        this.$http.delete('/product/del/' + row.id).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.currentPage = 1
          this.getProducts();
        });
      }).catch(() => {
      });
    }
    ,
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = '编辑'
      this.editForm = Object.assign({}, row);
      // 对fileList进行处理，用以显示图片
      // 先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      this.fileList = []
      if (this.editForm.resources) {
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg 对其进行分割
        let arr = this.editForm.resources.split(',')
        // 循环遍历
        for (let i = 0; i < arr.length; i++) {
          // 从fastDfs文件系统获取资源
          this.fileList.push({'url': 'http://123.207.27.208' + arr[i]})
        }
      }
      this.editFormVisible = true;
    },
    //显示新增界面
    handleAdd: function () {
      this.editFormVisible = true;
    },
    //编辑或新增
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //复制对象
            let para = Object.assign({}, this.editForm);
            console.log("para:" + this.editForm)
            this.$http.post('/product/saveOrUpdate', para).then((res) => {
              if (res.data.success) {
                this.editLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
              this.$refs['editForm'].resetFields();
              this.cancel();
            }).catch(e => {
              this.$message.error('请稍后重试【400】【405】')
              this.editLoading = false;
            }).finally(res => {
              this.getProducts();
            });
          });
        }
      });
    },


    handleSelectionChange(sels) {
      this.sels = sels;
    }
    ,
    //批量删除
    batchRemove: function () {
      const ids = this.sels.map(item => item.id);
      console.log(ids);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch('/product/delByBatch/', ids).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '批量删除成功',
            type: 'success'
          });
          this.sels = []
          this.currentPage = 1
          this.getProducts();
        });
      }).catch(() => {
        this.$message({
          message: '取消删除',
          type: 'info'
        });
      });
    }
  }
  ,
  mounted() {
    this.getProducts();
  }
}

</script>

<style scoped>

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>